package com.taoge.framework.util;


import com.taoge.framework.common.BaseToken;
import com.taoge.framework.constantsEnum.TokenTypeEnum;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by xuejingtao
 */
public class ControllerUtil {

    public static String getValueByKey(String key, HttpServletRequest request) {
        // header默认都是小写
        key = key.toLowerCase();
        String value = HeaderUtil.getHeaderValue(request, key);
        if (StringUtils.isEmpty(value)) {
            value = CookieUtil.getCookieByName(request, key);
        }
        if (StringUtils.isEmpty(value)) {
            value = request.getParameter(key);
        }
        return value;
    }

    public static String getToken(TokenTypeEnum tokenType, HttpServletRequest request) {
        return getValueByKey(tokenType.getKey(), request);
    }

    public static Long getUserId(TokenTypeEnum tokenType, HttpServletRequest request) {
        BaseToken token = getTokenEntity(tokenType, request);
        return null == token ? null : token.getUserId();
    }

    public static Integer getPageNum(HttpServletRequest request) {
        if (StringUtils.isEmpty(request.getParameter("pageNum"))) {
            return 1;
        } else {
            return Integer.parseInt(request.getParameter("pageNum"));
        }
    }

    public static Integer getPageSize(HttpServletRequest request) {
        if (StringUtils.isEmpty(request.getParameter("pageSize"))) {
            return 10;
        } else {
            return Integer.parseInt(request.getParameter("pageSize"));
        }
    }

    public static <T extends BaseToken> T getTokenEntity(TokenTypeEnum tokenType, HttpServletRequest request) {
        Object token = request.getAttribute(tokenType.getKey());
        return null == token ? null : (T) token;
    }

    public static void setToken(String token, TokenTypeEnum tokenType, String domain, HttpServletResponse response) {
        Cookie cookie = new Cookie(tokenType.name(), token);
        cookie.setPath("/");
        cookie.setDomain(domain);
        cookie.setHttpOnly(true);
        response.addCookie(cookie);
    }

    public static void cleanToken(TokenTypeEnum tokenType, HttpServletResponse response, String domain) {
        Cookie cookie = new Cookie(tokenType.name(), "");
        cookie.setPath("/");
        cookie.setDomain(domain);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }

}
